<template>
	<div class="personnelList agentAdd">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">
				<i class="lh lh-caiwu fw_100"></i>
			</el-breadcrumb-item>
			<el-breadcrumb-item>代理商管理</el-breadcrumb-item>
			<el-breadcrumb-item>{{ breadcrumb_name }}</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="content_Box box-shadow">
			<div>
				<h4 class="title border-bottom">{{ breadcrumb_name }}</h4>
				<div class="cont">
					<el-row>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>上级部门：</div>
								<div>
									<el-select v-model="query.parent_id" placeholder="上级部门" filterable>
										<el-option
											v-for="item in parent_list"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										></el-option>
									</el-select>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>代理商名称：</div>
								<div>
									<el-input v-model="query.name"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>负责人：</div>
								<div>
									<el-input v-model="query.principal"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>手机号：</div>
								<div>
									<el-input v-model="query.mobile"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name">备注：</div>
								<div>
									<el-input type="textarea" :rows="3" v-model="query.remark" placeholder="请输入内容"></el-input>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
				<h4 class="title border-bottom">关联商圈</h4>
				<div class="cont">
					<div v-for="(item, index) in allCities" :key="'only' + index" class="city-checkout">
						<el-checkbox
							class="all-selected"
							:indeterminate="item.isIndeterminate"
							v-model="item.selected"
							@change="handleCheckAllChange(item.selected, index)"
							>{{ item.city_name }}</el-checkbox
						>
						<div class="line"></div>
						<el-checkbox-group v-model="item.checkedCities">
							<el-checkbox
								v-for="(area, sum) in item.data"
								:label="area.id"
								:key="sum"
								:disabled="area.is_disabled"
								@change="handleCheckedCitiesChange(index, sum)"
								>{{ area.area_name }}</el-checkbox
							>
						</el-checkbox-group>
					</div>
				</div>
			</div>
			<div class="footer">
				<el-button round @click="back()">返回</el-button>
				<el-button type="primary" round @click="save()">保存</el-button>
			</div>
		</div>
	</div>
</template>

<script>
var common = require('../../../static/tool.js')
import { fetchCityAreaList, fetchAgentCreate, agentInfo, agentSetInfo, fetchAgentList } from '@/api/agent.js'
import { PHONE_REGEXP } from '@/utils/util.js'
export default {
	name: 'agentAdd',
	data() {
		return {
			manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')), //登录信息
			user_type: 1, //登录人员类型 1管理员 2账号
			url: common.url,
			head_url: common.head_url,
			breadcrumb_name: '新增代理商',
			sn: '',
			query: {
				parent_id: null,
				name: '',
				principal: '',
				mobile: '',
				remark: '',
				level: 1
			},

			allCities: [], //城市列表
			list: [], //人才账单列表
			parent_list: [] //上级部门
		}
	},
	mounted() {
		if (this.$route.query.sn) {
			this.sn = this.$route.query.sn
			this.breadcrumb_name = '编辑代理商'
		}
		this.user_type = this.manageInfo.user_info.type
		this.getCityAreaList()
		this.start()
	},
	methods: {
		start() {
			if (+this.user_type === 1) {
				this.parent_list.push({ name: '中服云', id: 0 })
				this.query.parent_id = 0
				return
			}
			this.getList()
			this.query.parent_id = ''
			this.query.level = 2
		},
		async getList() {
			try {
				let ret = await fetchAgentList({ page: 1, limit: 1000 })
				this.parent_list = ret.list.map(it => {
					return { name: it.name, id: +it.id }
				})
				// 编辑进来并且父级id 是中服云
				if (+this.query.parent_id === 0 && this.sn) {
					let ret = this.parent_list.filter(it => it.id == 0)
					if (ret.length == 0) this.parent_list.unshift({ name: '中服云', id: 0 })
				}
			} catch (err) {
				console.log('err:', err)
			}
		},
		async getAgentInfo() {
			try {
				let res = await agentInfo({
					sn: this.sn
				})
				res.area_id.forEach(it => {
					this.allCities.forEach(city => {
						city.data.forEach(area => {
							if (area.id == it) {
								city.checkedCities.push(it)
								area.is_disabled = false
							}
						})
						let checkedCount = city.checkedCities.length
						city.selected = checkedCount === city.data.length
						city.isIndeterminate = checkedCount > 0 && checkedCount < city.data.length
					})
				})
				this.query.name = res.name
				this.query.principal = res.principal
				this.query.remark = res.remark
				this.query.mobile = res.mobile
				this.query.parent_id = +res.parent_id
				this.getList()
			} catch (err) {
				console.log(err)
			}
		},
		// 添加/编辑/保存
		async save(params = {}) {
			try {
				console.log(this.query)
				if (!this.query.name || !this.query.principal || !this.query.mobile) {
					return this.$message.error('请填写必填项！')
				}

				if (!this.user_type === 1 && this.query.parent_id == '') {
					return this.$message.error('请填写必填项！')
				}

				if (!PHONE_REGEXP.test(this.query.mobile)) {
					return this.$message.error('请填写正确的手机号码')
				}

				let city_id = []
				let area_id = []
				this.allCities.forEach(it => {
					if (it.checkedCities.length > 0) {
						city_id.push(it.city_id)
						area_id = [...area_id, ...it.checkedCities]
					}
				})

				if (this.sn) {
					await agentSetInfo({
						...this.query,
						city_id: city_id.join(','),
						area_id: area_id.join(','),
						sn: this.sn
					})
				} else {
					await fetchAgentCreate({
						...this.query,
						city_id: city_id.join(','),
						area_id: area_id.join(',')
					})
				}
				this.$message.success(`${this.sn ? '修改成功' : '添加成功'}`)
				this.back()
			} catch (err) {
				console.log(err)
			}
		},

		async getCityAreaList() {
			try {
				let ret = await fetchCityAreaList()
				ret.list.forEach(it => {
					// 标识 true 代表禁用城市选项   false 打开
					// let type = true

					it.selected = false
					it.checkedCities = []
					it.isIndeterminate = false
					it.selected = false
					it.data.forEach(x => {
						x.is_disabled = x.already_set == 1 ? true : false
						// if (!x.is_disabled) type = false
					})

					// it.is_disabled = type ? true : false
				})
				console.log(ret.list)
				this.allCities = ret.list
				// 编辑进来调取详情
				if (this.sn) this.getAgentInfo()
			} catch (err) {
				console.log('err:', err)
			}
		},

		handleCheckAllChange(val, index) {
			const allCities = this.allCities[index]
			if (val) {
				allCities.data.forEach(item => {
					item.selected = true
					if (!item.is_disabled) allCities.checkedCities.push(item.id)
				})
			} else {
				allCities.checkedCities = []
			}
			allCities.isIndeterminate = false
		},
		handleCheckedCitiesChange(index, sum) {
			// console.log(index + ',+,' + sum)
			const allCities = this.allCities[index]
			allCities.data[sum].selected = !allCities.data[sum].selected

			let checkedCount = allCities.checkedCities.length
			// console.log('checkedCount', checkedCount)
			allCities.selected = checkedCount === allCities.data.length
			allCities.isIndeterminate = checkedCount > 0 && checkedCount < allCities.data.length
		},

		back() {
			this.$router.go(-1)
		}
	},
	filters: {}
}
</script>

<style scoped>
.flex-container {
	display: flex;
	line-height: 40px;
}
.content_Box {
	padding: 10px;
}
.content_Box .title {
	padding-bottom: 10px;
}
.content_Box .cont {
	padding: 20px 0;
	font-size: 14px;
}
.content_Box .label-name {
	width: 120px;
	text-align: right;
	color: #666666;
}
.agentAdd .line {
	height: 5px;
}
.city-checkout {
	border-bottom: 1px dashed #ebebeb;
	padding: 10px 0;
}
.city-checkout:last-child {
	border-bottom: none;
}
.all-selected {
	color: #222222;
}
.footer {
	padding: 50px 0 50px 200px;
}
.footer button {
	width: 100px;
	margin-left: 40px;
}
</style>
<style>
.agentAdd .el-input__inner,
.agentAdd .el-textarea__inner {
	width: 300px;
}
.agentAdd .el-checkbox-group .el-checkbox {
	min-width: 120px;
	margin-bottom: 5px;
}
</style>



// WEBPACK FOOTER //
// src/components/agent/AgentAdd.vue